/**
 * 初始化整体流量图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/radar');
    var zrnumber = require('echarts/util/number');

    var myChart = ec.init(document.getElementById('cateRadarOne')); 


    var myOption = {
        timeline:{
            data:[
                '2002-01-01','2003-01-01','2004-01-01'
            ],
            label : {
                formatter : function(s) {
                    return s;
                }
            },
            autoPlay : false,
            playInterval : 1000
        },  
        options:[
            {
                title : {
                    text: '租房 vs 二手房',
                    subtext: '分城市指标对比'
                },
                tooltip : {
                    trigger: 'axis',
                    formatter: function (params,ticket,callback) {
                                var res = params[0].indicator;
                                for (var i = 0, l = params.length; i < l; i++) {
                                    var realVal = params[i].value;
                                    if(params[i].indicator!="展现" && params[i].indicator != "点击"){
                                        realVal = (realVal/10).toFixed(2);  //数据放大了10倍
                                    }
                                    res += '<br/>' + params[i].name + ' : ' + realVal;
                                }
                                return res;
                     }                     
                },
                legend: {
                    x : 'center',
                    data:['租房','二手房']
                },
                toolbox: {
                    show : true,
                    feature : {
                        mark : {show: true},
                        dataView : {show: false, readOnly: true},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                calculable : true,
                polar : [
                    {
                        indicator : [
                            {text : '展现'},
                            {text : '点击'},
                            {text : 'ACP'},
                            {text : 'CPM2'},
                            {text : 'CTR2'}
                        ]
                    }
                ],
                series : [
                    {
                        name: '分城市指标对比',
                        type: 'radar',
                        itemStyle: {
                            normal: {
                                areaStyle: {
                                    type: 'default'
                                }
                            }
                        },
                        data : [
                            {
                                value : [9000,90000, 1.1, 8, 43],
                                name : '租房'
                            },
                            {
                                value : [7500, 72000, 0.8, 9, 38],
                                name : '二手房'
                            }
                        ]
                    }
                ]
            },
            {
                series : [
                    {
                        name: '分城市指标对比',
                        type: 'radar',
                        itemStyle: {
                            normal: {
                                areaStyle: {
                                    type: 'default'
                                }
                            }
                        },
                        data : [
                           
                        ]
                    }
                ]               
            }
            ]
        };

    //[cate1, cate2]
    var cateArr = [];


    function setLegendNameMap(cateCmp_cates){
        cateArr =cateCmp_cates;
        myOption.options[0].legend.data = cateArr;
   }

    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(businessName,eventType){
        var dateGrp = $('#cateRadarOpt').attr('dateGrp');
        var statType = $('#cateRadarOpt').attr('statType');
        var stat_date =  $('#time_input_cateRadar').val();
        var  is_vip = $('#cateRadar_index').val();
        var cates_radar = $('#cateRadar_cates').val();
        var cateCmp_cates = cates_radar.split(",");
        if(cateCmp_cates.length != 2){
            alert("必须选择两个对比类别!");
            return;
        }
        cateArr =cateCmp_cates;

        myChart.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/income/ajax/cateRadar',
            type: 'post',
            async: true,
            data: {"businessName":businessName,"is_vip":is_vip,"dateGroup":dateGrp,"dateVal":stat_date,"statType":statType,"cates_radar":$('#cateRadar_cates').val()},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                myOption.timeline.data = data.time;

              
                $.each(data.dataList,function(i,cateData){
                    var series_local =  [
                        {
                            name: '分城市指标对比',
                            type: 'radar',
                            itemStyle: {
                                normal: {
                                    areaStyle: {
                                        type: 'default'
                                    }
                                }
                            },
                            data : cateData
                        }
                    ];
                    if(i == 0){
                        myOption.options[i].series = series_local;                  
                    }else{
                         myOption.options[i] = { "series" : series_local};
                    }
                });
                myOption.options[0].legend.data = cateArr;
                myOption.options[0].title.text  = cateArr[0] + " VS " + cateArr[1];  

                if(eventType == 1 || eventType == 2){
                    // console.log(myOption);
                    myChart.setOption(myOption,true);
                }
                myChart.hideLoading();
                $('#time_input_cateRadar').val(data.time[data.time.length -1]);
                loadTableData(data.time[data.time.length -1]);
            },
            error : function() {
                myChart.hideLoading();
            }
        });
    }

    //加载27个直销城市当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"cate_name":0,"disp":1,"click":1,"acp":1,"cpm2":1,"ctr2":1};
    function loadTableData(stat_date){
        var dateGrp = $('#cateRadarOpt').attr('dateGrp');
        var statType = $('#cateRadarOpt').attr('statType');
         var  is_vip = $('#cateRadar_index').val();
        var businessName = cate;
        $.ajax({
            url: '/dashboard/income/ajax/cateRadar',
            type: 'post',
            async: true,
            data:{"dateGroup":dateGrp,"is_vip":is_vip,"statType":statType,"dateVal":stat_date, "businessName":businessName,"dataType":"table"},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var htmlRows = "";
                $.each(resultList,function(i,vo){
                    htmlRows += "<tr>";

                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += formatNum(vo[col]);
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#cateRadarTable tr:gt(0)').remove();
                $('#cateRadarTable_date').text(stat_date.replace(/\-/g,"."));
                $('#cateRadarTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }
       

    var zrUtil = require('zrender/tool/util');


    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }

    function formatShowDate(yyyymmdd){
        var dateGrp = $('#cateCmpOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#cateCmpOption').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

    //绑定书刷新按钮点击事件
    $("#refreshCateRadar_btn").click(function(){
        var type = 2;
        EC.show(cate,type);
    });

    $(":button.btnCateRadar[dateGrp]").click(function(){
        changeDateGrp(this);
        if($(this).attr('dateGrp')=='week_begin'){
            $('#cateRadarDateDiv').hide();
        }else{
            $('#cateRadarDateDiv').show();
        }
        EC.show(cate,1);
    });


    $('#time_input_cateRadar').datepicker({
        startView: "month",
        minView: "year",
        maxView: "month",
        format: "yyyy-mm-dd",
        clearBtn: false,
        language: "zh-CN",
        autoclose: true,
        startDate:"2014-01-01",
        todayHighlight: false,
        minViewMode:0,
        orientation: "top left"
    });
    
    $(function(){
        $("#cateRadar_mul").multiselect({
            header:false,
            height:300,
            minWidth:140,
            noneSelectedText: "--请选择--",
            checkAllText: "disabled",
            uncheckAllText: '清空',
            selectedList:2,
            click: function(event, ui){
                var array_of_checked_values = $("#cateRadar_mul").multiselect("getChecked").map(function(){
                   return this.value;    
                }).get();
                var warning = $(".message");
                if(array_of_checked_values.length > 2){
                    return false;
                }
                 // $("#cateRadar_cates").val(array_of_checked_values.join(","));
            },
            uncheckAll: function(){
                $("#cateRadar_cates").val('');
            },
            selectedText: function(numChecked, numTotal, checkedItems){
                var two='';
                /*
                    js数组的map方法和 $.map(arr,callback)将一个数组中的元素转换到另一个数组中;
                    $(selector).map(arr,callback)返回jquery对象 $(selector).map(arr,callback).get()使用 get() 来处理返回的对象以得到基础的数组
                */
               if(numChecked > 2){
                        return false;
                }
                var idcs=checkedItems.map(function(element){
                    return element.value; 
                });
                $("#cateRadar_cates").val(idcs.join(','));

                return idcs.join(' , ');
            }
       });
    }); 

    var EC={
        show:show,
        resize:function(){myChart.resize();}
    };
    return EC;
});

